package com.jetgege.smartbox.AddBox;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.jetgege.smartbox.Base.BaseActivity;
import com.jetgege.smartbox.FirstUse.FirstUserActivity;
import com.jetgege.smartbox.R;
import com.jetgege.smartbox.Tools.BluetoothHelper;
import com.jetgege.smartbox.Tools.Common;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jetgege.smartbox.Base.App.connectedDevices;

public class AddDeviceActivity extends BaseActivity {

    @BindView(R.id.adddevice_toolbar)
    Toolbar adddeviceToolbar;
    //List<BlueModel> mBlueModels = new ArrayList<>();
    @BindView(R.id.lv_ScanDeviceList)
    ListView lvScanDeviceList;
    ScanAdapter scanAdapter;
    List<BluetoothDevice> devices = new ArrayList<>();
    String action=null;

    Handler handler;
    final int ACTION_BLE_DEFAULT = 1000;
    final int ACTION_BLE_FOUND = 1001;
    final int ACTION_BLE_DISCOVERY_STARTED = 1002;
    final int ACTION_BLE_DISCOVERY_FINISHED = 1003;
    final int ACTION_BLE_CONNECTED = 1004;
    final int ACTION_BLE_DISCONNECTED = 1005;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_device;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initValue();
        eventHandle();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销蓝牙通知
        BluetoothHelper.unRegisterBluetoothBroadcast(AddDeviceActivity.this,mReceiver);
    }

    private void initValue() {
        //注册蓝牙通知
        BluetoothHelper.registerBluetoothBroadcast(AddDeviceActivity.this,mReceiver);
        action = getIntent().getAction();
//        for (int i = 0; i < 20; i++) {
//            BlueModel model = new BlueModel();
//            model.setName("蓝牙" + String.valueOf(i));
//            model.setId("23238SEW82" + String.valueOf(i));
//            mBlueModels.add(model);
//        }

        adddeviceToolbar.setTitle("添加盒子");
        setSupportActionBar(adddeviceToolbar);
        // Navigation Icon 要設定在 setSupoortActionBar 才有作用
        // 否則會出現 back button
        if (!action.equals("StartActivity")) adddeviceToolbar.setNavigationIcon(R.drawable.bar_back_btn);

        //scanAdapter = new ScanAdapter(mBlueModels);
        scanAdapter = new ScanAdapter(devices);
        lvScanDeviceList.setAdapter(scanAdapter);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ACTION_BLE_DISCOVERY_FINISHED://扫描结束
                        if (scanConnect.isShowing()) scanConnect.dismiss();
                        scanAdapter.notifyDataSetChanged();//刷新列表
                        break;
                    case ACTION_BLE_CONNECTED://连接成功
                        hud.setLabel("连接成功！");
                        jumpAuthentication(hud, 1000);
                        break;
                    case ACTION_BLE_DISCONNECTED://连接成功
                        hud.setLabel("连接失败！");
                        Common.dismissHUD(hud);
                        break;

                }
            }
        };

        lvScanDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                connectDev();
                connectedDevices = devices.get(position);
                BluetoothHelper.conn(connectedDevices, new BluetoothHelper.CharacteristicCallBack() {
                    @Override
                    public void onCallBack(byte[] data) {}
                });

            }
        });
        //扫描设备
        //if (action.equals("StartActivity"))
            scanTips();
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String actionBack = intent.getAction();
            Message msg = handler.obtainMessage();
            if (BluetoothHelper.ACTION_BLE_DISCOVERY_STARTED.equals(actionBack))//开始扫描
                msg.what = ACTION_BLE_DISCOVERY_STARTED;
            else if (BluetoothHelper.ACTION_BLE_DISCOVERY_FINISHED.equals(actionBack))//扫描结束
                msg.what = ACTION_BLE_DISCOVERY_FINISHED;
            else if (BluetoothHelper.ACTION_BLE_CONNECTED.equals(actionBack))//连接成功
                msg.what = ACTION_BLE_CONNECTED;
            else if (BluetoothHelper.ACTION_BLE_DISCONNECTED.equals(actionBack))//断开连接
                msg.what = ACTION_BLE_DISCONNECTED;
            else
                msg.what = ACTION_BLE_DEFAULT;

            handler.sendMessage(msg);
        }
    };

    private void eventHandle() {
        adddeviceToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
            }
        });

    }

    //搜索提示
    KProgressHUD scanConnect = null;
    private void scanTips() {
        if (devices.size() > 0) devices.clear();
         scanConnect = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在搜索设备...")
                .setCancellable(true)
                .show();
        BluetoothHelper.scanLeDevice(mLeScanCallback);
    }

    /**
     * 扫描回调
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    String deviceName = device.getName();
                    if (deviceName == null) return;
                    if (deviceName.length() < 10) return;
                    String regexChar = (String) deviceName.subSequence(0, 7);
                    if (regexChar.equals("Goockr-")) {
                        if (scanConnect.isShowing()) scanConnect.dismiss();
                        if (!devices.contains(device))
                            devices.add(device);
                    }
                    scanAdapter.notifyDataSetChanged();
                }
            };

    @OnClick(R.id.bt_ScanDev)
    public void onViewClicked() {
//        KProgressHUD hud = KProgressHUD.create(this)
//                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
//                .setLabel("正在扫描...")
//                .setCancellable(true);
//        scheduleDismiss(hud, 4000);
//        hud.show();
        //扫描设备
        scanTips();
    }

    KProgressHUD hud = null;
    private void connectDev() {
           hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("连接设备...")
                .setCancellable(true)
                .show();
    }
    public void jumpAuthentication(final KProgressHUD hud, int time) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hud.dismiss();
                if (action.equals("MainActivity"))
                    startActivity(new Intent(AddDeviceActivity.this, AuthenticationActivity.class));
                else if (action.equals("StartActivity"))
                    startActivity(new Intent(AddDeviceActivity.this, FirstUserActivity.class));
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                finish();
            }
        }, time);
    }

}
